package com.zhxxfwzx.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @title: JwtTokenUtils
 * @Author LiJing
 * @Date: 2021/6/84:28 下午
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "lijing.jwt")
public class JwtTokenUtils {
    private String secret = "secret";
    private long expiration = 604800*1000;
    private String header = "Authorization";

    /**
     * 从数据声明生成令牌
     * @param claims 数据声明
     * @return token
     */
    private String generateToken(Map<String, Object> claims){
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 生成令牌
     * @param userDetails userDetails用户
     * @return token
     */
    public String generateToken(UserDetails userDetails){
        Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put(Claims.ISSUED_AT, new Date());
        return generateToken(claims);
    }

    /**
     * 从token中获取数据声明
     * @param token 令牌token
     * @return claims数据声明
     */
    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            claims = null;
        }
        return claims;
    }


    /**
     * 判断token是否过期
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token){
        try {
            Claims claims = getClaimsFromToken(token);
            Date expireation = claims.getExpiration();
            return expireation.before(new Date());
        }catch (Exception e){
            return true;
        }
    }


    /**
     * 从令牌token中获取用户名
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token){
        String username;
        try {
            username = getClaimsFromToken(token).getSubject();
        }catch (Exception e){
            username = null;
        }
        return username;
    }

    /**
     * 刷新令牌，其实是重置签发时间
     * @param token 待刷新的令牌
     * @return 刷新后的令牌
     */
    public String refreshToken(String token){
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(claims);
        }catch (Exception e){
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 验证令牌
     * @param token 令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(String token, UserDetails userDetails){
        User user = (User) userDetails;
        String username = getUsernameFromToken(token);
        return (username.equals(user.getUsername()) && !isTokenExpired(token));
    }

}
